<template>
  <!-- 方案编制模板and技术交底模板 -->
  <div>
    <searchData :searchData="searchArr" @search="search"></searchData>
    <a-card>
      <!-- 表格 -->
      <list-table ref="table"
                  :columns="columns"
                  :request="loadData"
                  startIndex="0"
                  :exportConfig="{ use: true, select: expTitle, all: expTitle }" 
                  :exportPermission="{ select: btnFn.exp(), all: btnFn.exp() }">
        <!-- 新增 -->
        <a-button v-btnPermission="btnFn.add()" slot="prefix" class="mb12" icon="plus" type="primary" @click="handleManage('add')">新增</a-button>
        <!-- 下载附件 -->
        <template slot="suffix" slot-scope="scoped">
          <a-button
            v-btnPermission="btnFn.bat()"
            :loading="downLoading"
            class="mb12"
            icon="cloud-download"
            :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
            type="primary"
            @click="handleManage('downZip', scoped.selectedRowKeys)"
            >批量下载附件</a-button
          >
        </template>
        <span slot="operation" slot-scope="text, record">
          <MoreButton>
            <!-- <MoreButton> -->
            <a v-btnPermission="btnFn.look()" @click="handleManage('look', record)">查看</a>
            <!-- 编辑 -->
            <template>
              <a @click="handleManage('edit', record)" v-btnPermission="btnFn.edit()">编辑</a>
            </template>
            <a v-btnPermission="btnFn.del()" @click="handleManage('delete', record)">删除</a>
          </MoreButton>
        </span>
      </list-table>
    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import BasePage from '@/views/basePage' // 基础配置
import { findListByMainPage, findListByMainDel, findListByMainDown } from '@/api/technical/planHighlights'
import MoreButton from '@/components/MoreButton'
import { add } from 'lodash'

const columns = [
  {
    title: '序号',
    width: '80px',
    dataIndex: 'index',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '文件名称',
    dataIndex: 'fileName',
    ellipsis: true,
    scopedSlots: { customRender: 'fileName' }
  },
  {
    title: '方案分类',
    dataIndex: 'technicalName',
    ellipsis: true
  },
  {
    title: '上传人',
    dataIndex: 'uploadUserName'
  },
  {
    title: '上传时间',
    dataIndex: 'uploadDate'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '200px',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    STable,
    MoreButton
  },
  data() {
    this.columns = columns
    return {
      queryParam: {},
      downLoading:false,

      loadData: async parameter => {
        let requestParameters = Object.assign({}, parameter, { query: this.queryParam })
        requestParameters.query.typeId = this.activeKey === '2' ? 0 : 1
        return findListByMainPage(requestParameters).then(res => {
          res.data = res.data.map((v, index) => {
            v.index = index + 1
            return v
          })
          return res
        })
      },
      btnFn: {
        add: () => {
          return this.activeKey === '2' ? 'tm_053_add_01' : 'tm_054_add_01'
        },
        edit: () => {
          return this.activeKey === '2' ? 'tm_053_edi_02' : 'tm_054_edi_02'
        },
        look: () => {
          return this.activeKey === '2' ? 'tm_053_loo_04' : 'tm_054_loo_04'
        },
        del: () => {
          return this.activeKey === '2' ? 'tm_053_del_03' : 'tm_054_del_03'
        },
        exp: () => {
          return this.activeKey === '2' ? 'tm_053_exp_05' : 'tm_054_exp_05'
        },
        bat: () => {
          return this.activeKey === '2' ? 'tm_053_bat_06' : 'tm_054_bat_06'
        },
      },
      searchArr: [
        {
          name: '文件名称',
          type: 'input',
          value: 'fileName'
        },
        {
          name: '方案分类',
          type: 'input',
          value: 'technicalName'
        },
        {
          name: '上传人',
          type: 'input',
          value: 'uploadUserName'
        },

        {
          name: '上传时间',
          type: 'dateRange',
          value: 'uploadTime',
          attr: {
            //搜索设置默认搜索日期
            defaultValue: [],
            rangeFormat: ['uploadDateStart', 'uploadDateEnd']
          }
        }
      ]
    }
  },
  computed: {
    expTitle() {
      return this.activeKey === '2' ? '方案编制模板' : '技术交底模板'
    }
  },
  props: {
    activeKey: {
      type: String
    }
  },
  methods: {
    //搜索
    search(value) {
      value && (this.queryParam = value)
      if (!value.fillingInTimeBegin) {
        delete this.queryParam.fillingInTimeBegin
        delete this.queryParam.fillingInTimeEnd
      }
      this.$refs.table.refresh(true)
    },

    /**
     *@desc  打开弹出窗
     *@param {}
     */
    selectTechnicalClassFn() {
      this.selectTechnicalClassVisible = true
    },
    /**
     *@desc  新增  编辑  查看 删除 下载
     *@param {}
     */
    handleManage(type, record = {}) {
      const commonHandler = () => {
        this.$router.push({
          name: 'updateTemplate',
          query: {
            type: type,
            activeKey: this.activeKey,
            id: record.id || ''
          }
        })
      }
      const typeMap = {
        add: commonHandler,
        edit: commonHandler,
        look: commonHandler,
        delete: () => {
          this.handleDelete(record)
        },
        downZip: () => {
          this.downZipFc(record)
        }
      }
      typeMap[type] && typeMap[type]()
    },
    /**
     *@desc  下载
     *@param {}
     */
    async downZipFc(ids) {
      this.downLoading = true;
      let params = { ids, typeId: this.activeKey === '2' ? 0 : 1, urlStr: window.location.origin }
      let res = await findListByMainDown(params)
      this.downLoading = false;
      this.handleDownload(res)
    },
    /**
     * 转义下载
     * @param parameter
     */
    handleDownload(res) {
      const blob = new Blob([res.data])
      console.log(res,12222)
      console.log(decodeURIComponent(res.headers['content-disposition']),2222)
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 1) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    /**
     *@desc  删除
     *@param {}
     */
    handleDelete(data) {
      let that = this
      that.$confirm({
        title: '警告提醒！',
        content: '确定删除？',
        okType: 'danger',
        async onOk() {
          let res = await findListByMainDel(data.id)
          if (res?.data?.code === 200) {
            that.$message.success('删除成功')
            that.$refs.table.refresh(true)
          } else {
            that.$message.error('删除失败')
          }
        },
        onCancel() {}
      })
    }
  }
}
</script>
